package com.shuqi.activity;

import java.lang.reflect.Field;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.BookdetailsCatalogAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.BookCatalogController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookCataLogDao.CatalogChangerActivityListener;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/***
 * intent String 参数 bookId
 * 
 * @author yanghuawei
 * 
 */
public class BookCatalogActivity extends ActivityBase implements IEventListener, OnClickListener,
        OnItemClickListener ,CatalogChangerActivityListener{
    private static final String TAG = "BookCatalogActivity";
    private final int Mgs_initView = 0;
    private final int Mgs_Data_Ok = 1;
    private final int Mgs_Data_error = 2;

    private BookCatalogController mController;
    private BookData mCatalog;
    /** 书籍ID */
    private String mBookId;

    private BookdetailsCatalogAdapter mAdapter;
    private ListView mListView;
    private View mLoadingView;
    private CommonTitle mTitle;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Mgs_initView:
                    activityLogicForward();
                    break;
                case Mgs_Data_Ok:
                    showErrorPage(false);
                    activityInitData();
                    break;
                case Mgs_Data_error:
                    showErrorPage(true);
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController =
                (BookCatalogController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_BOOKCATALOG, this);
        mController.addEventListener(this);
        setContentView(R.layout.act_bookcatalog);
        if (getIntent() != null) {
            mBookId = getIntent().getStringExtra(BookCoverActivity.INTENT_NAME_BOOKID);
        } else {
            showMsg("intent 参数有误");
            finish();
        }
        BookCataLogDao.getInstance().registerCatalogActivity(this);
        handler.sendEmptyMessage(Mgs_initView); // 通知初始化View
    }

    @Override
    protected void onResume() {
        loadData();
        super.onResume();
    }

    @Override
    public void onEvent(int event, Object data) {
        Log4an.i(TAG, "-------------------获取目录----------------");
        // 从数据库读取的
        mCatalog = (BookData) data;
        if (mCatalog != null && mCatalog.getInfos() != null && mCatalog.getInfos().size() > 0) {
            handler.sendEmptyMessage(Mgs_Data_Ok);
        } else {
            handler.sendEmptyMessage(Mgs_Data_error);
        }
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setImageListener(this);
        mListView = (ListView) findViewById(R.id.bookdetails_catalog_listview);
        mListView.setOnItemClickListener(this);
        setScrollBar(mListView, R.drawable.fast_bar_normal);
        mLoadingView = findViewById(R.id.include_loading);
        mLoadingView.setVisibility(View.VISIBLE);
    }

    /***
     * 显示网络错误页面
     * 
     * @param isNetError
     */
    private void showErrorPage(boolean isNetError) {
        if (isNetError) {
            findViewById(R.id.bookdetails_catalog_listview).setVisibility(View.GONE);
        } else {
            findViewById(R.id.bookdetails_catalog_listview).setVisibility(View.VISIBLE);
        }
        findViewById(R.id.include_error).setVisibility(isNetError ? View.VISIBLE : View.GONE);
        if(Util.isNetworkConnected(this)){//解析失败
            ((ImageView)findViewById(R.id.nonet_image)).setImageResource(R.drawable.limit_nodata);
            ((TextView)findViewById(R.id.nonet_text)).setText("目录获取失败，请重试");
        }else{
            ((ImageView)findViewById(R.id.nonet_image)).setImageResource(R.drawable.icon_network);
            ((TextView)findViewById(R.id.nonet_text)).setText("网络不给力,请重试");
        }
        
        findViewById(R.id.retry).setOnClickListener(isNetError ? this : null);
        mLoadingView.setVisibility(View.GONE);
    }



    /** 发送请求目录的请求 */
    private void loadData() {
        //TODO
        //Toast.makeText(this, "-------", 0).show();
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
        mController.handle(0, mBookId); // 通知加载数据
    }

    @Override
    public void activityInitData() {
        if (mCatalog != null) {
            if (BookInfo.BOOK_HIDEN.equals(mCatalog.getHide())) {
                showMsg(getString(R.string.error_bookswitch_ishide));
                finish();
                return;
            } else if (BookInfo.HIDEN == mCatalog.getCoverIsopen()) {
                showMsg(getString(R.string.error_bookswitch_coverisclose));
                finish();
                return;
            }
            if (mAdapter == null) {
                mAdapter = new BookdetailsCatalogAdapter(this, mCatalog.getInfos());
            } else {
                mAdapter.setList(mCatalog.getInfos());
            }
            BookMarkInfo info = getBookMark();
            int position = 0;
            String chapterId = null;
            if (info != null) {
                chapterId = info.getChapterId();
                position = mAdapter.getPosition(chapterId);
                mListView.setSelection(position);
                mAdapter.setSelectorChapterId(chapterId);
            }
            mListView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(position);
            mAdapter.setSelectorChapterId(chapterId);
        }
    }

    /**
     * 修改listview默认的滑动条
     */
    private void setScrollBar(ListView listview, int imgId) {
        Log4an.e(TAG, "获取到的版本号：" + Util.getOSVersion());
        if (Util.getOSVersion() >= 19) {
            // setScrollBar_forSDK19(listview);
            return;
        }
        try {
            Field f = AbsListView.class.getDeclaredField("mFastScroller");
            f.setAccessible(true);
            Object o = f.get(listview);
            f = f.getType().getDeclaredField("mThumbDrawable");
            f.setAccessible(true);
            Drawable drawable = (Drawable) f.get(o);
            drawable = getResources().getDrawable(imgId);
            f.set(o, drawable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改android 4.4 listview默认的滑动条 暂时不可行 setScrollBar setScrollBar_forSDK19
     */
    private void setScrollBar_forSDK19(final ListView listview) {
        listview.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_FLING:// 快速滑动
                        // 这里setFastScrollEnabled(true) 不生效

                        // listview.setFastScrollAlwaysVisible(true);
                        break;
                    case SCROLL_STATE_IDLE:// 静止不动
                        // listview.setFastScrollAlwaysVisible(true);
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:// 缓慢滑动
                        // listview.setFastScrollAlwaysVisible(true);

                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {}
        });
        return;
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mController.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                loadData();
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        loadData();

                    }
                });
                break;
        }
    }

    /**
     * 获取书签
     * 
     * @return
     */
    private BookMarkInfo getBookMark() {
        BookMarkInfo info =
                BookMarkInfoDao.getInstance().getBookMark(null, mBookId,
                        MyAccountManager.getInstance(this).getUserId(),
                        BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
        return info;
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // return false;
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BookCataLog info = mAdapter.getInfoFromCataLog(position);
        BookMarkInfo markInfo = new BookMarkInfo();
        markInfo.setUserId(MyAccountManager.getInstance(this).getUserId());
        markInfo.setBookId(mBookId);
        markInfo.setChapterId(info.getChapterId());
        markInfo.setBookName(mCatalog.getBookName());
        markInfo.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
        markInfo.setBookCoverImgUrl(mCatalog.getCoverImg());
        EnterBookContent.jumpToBookContentByBookMark(this, markInfo, -1);
        StatisticsUtils.onEvent(StatisticsEventID.BOOKCOVER_CATALOG_JUMPREAD);
    }

    @Override
    public void onCatalogChanger() {
        mController.handle(0, mBookId);
    }

}
